package org.ccay.web.support.servlet;

import java.io.IOException;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 支持浏览器缓存的Servlet
 * 
 * 子类需要指定缓存时间，以秒为单位
 * 
 */
public abstract class CacheServlet extends HttpServlet {

	private static final long serialVersionUID = 4345752069052477570L;	
	
	//返回缓存时间，以秒为单位
	protected abstract int getCacheMaxAge();
	
	public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
		long lastModifiedTime = Calendar.getInstance().getTimeInMillis();
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpServletResponse httpResponse = (HttpServletResponse)response;
		if("GET".equals(httpRequest.getMethod())){
			setLastModifiedTime(lastModifiedTime);
			setCache(httpResponse,lastModifiedTime);
		}
		super.service(request, response);
	}
	
	//设置更新时间，更新条件是超出缓存时间
	private void setLastModifiedTime(long lastModifiedTime){
		long now = Calendar.getInstance().getTimeInMillis();
		if((now - lastModifiedTime) / 1000L > getCacheMaxAge()){
			lastModifiedTime = now;
		}
	}
	
	//设置缓存有效时间
	private void setCache(HttpServletResponse response,long lastModifiedTime) {
		int cacheMaxAge = getCacheMaxAge();  // 单位秒
		response.setHeader("Cache-Control", "max-age=" + cacheMaxAge);
		response.setHeader("Pragma", "cache");
		response.setDateHeader("Expires", lastModifiedTime + cacheMaxAge * 1000L);
	}
	
	
}
